package com.zhentao.controller;

import com.zhentao.service.ChatGroupMessageService;
import com.zhentao.vo.Result;
import com.zhentao.websocket.pojo.ChatGroupMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 群聊消息控制器
 * 处理群聊消息相关的REST API接口
 */
@RestController
@RequestMapping("/api/group-chat")
public class ChatGroupController {

    @Autowired
    private ChatGroupMessageService chatGroupMessageService;

    /**
     * 获取群聊历史消息
     * GET /api/group-chat/messages?groupId=xxx&page=0&size=30
     */
    @GetMapping("/messages")
    public Result<Map<String, Object>> getGroupChatMessages(
            @RequestParam Long groupId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "30") int size) {
        
        try {
            if (groupId == null) {
                return Result.fail("群组ID不能为空");
            }
            
            List<ChatGroupMessage> messages = chatGroupMessageService.getGroupChatHistory(groupId, page, size);
            
            Map<String, Object> result = new HashMap<>();
            result.put("messages", messages);
            result.put("groupId", groupId);
            result.put("page", page);
            result.put("size", size);
            result.put("total", messages.size());
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.fail("获取群聊消息失败: " + e.getMessage());
        }
    }

    /**
     * 获取群聊最新消息
     * GET /api/group-chat/latest?groupId=xxx
     */
    @GetMapping("/latest")
    public Result<ChatGroupMessage> getGroupLatestMessage(@RequestParam Long groupId) {
        try {
            if (groupId == null) {
                return Result.fail("群组ID不能为空");
            }
            
            ChatGroupMessage latestMessage = chatGroupMessageService.getLatestMessage(groupId);
            return Result.success(latestMessage);
        } catch (Exception e) {
            return Result.fail("获取群聊最新消息失败: " + e.getMessage());
        }
    }

    /**
     * 保存群聊消息
     * POST /api/group-chat/save
     */
    @PostMapping("/save")
    public Result<ChatGroupMessage> saveGroupMessage(@RequestBody ChatGroupMessage message) {
        try {
            if (message == null) {
                return Result.fail("消息内容不能为空");
            }
            
            ChatGroupMessage savedMessage = chatGroupMessageService.saveMessage(message);
            return Result.success(savedMessage);
        } catch (Exception e) {
            return Result.fail("保存群聊消息失败: " + e.getMessage());
        }
    }

    /**
     * 批量保存群聊消息
     * POST /api/group-chat/batch-save
     */
    @PostMapping("/batch-save")
    public Result<Map<String, Object>> batchSaveGroupMessages(@RequestBody List<ChatGroupMessage> messages) {
        try {
            if (messages == null || messages.isEmpty()) {
                return Result.fail("消息列表不能为空");
            }
            
            List<ChatGroupMessage> savedMessages = chatGroupMessageService.saveMessages(messages);
            
            Map<String, Object> result = new HashMap<>();
            result.put("savedCount", savedMessages.size());
            result.put("messages", savedMessages);
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.fail("批量保存群聊消息失败: " + e.getMessage());
        }
    }

    /**
     * 删除群聊消息（软删除）
     * DELETE /api/group-chat/{messageId}
     */
    @DeleteMapping("/{messageId}")
    public Result<String> deleteGroupMessage(@PathVariable String messageId) {
        try {
            if (messageId == null || messageId.trim().isEmpty()) {
                return Result.fail("消息ID不能为空");
            }
            
            boolean deleted = chatGroupMessageService.deleteMessage(messageId);
            if (deleted) {
                return Result.success("消息删除成功");
            } else {
                return Result.fail("消息删除失败，消息不存在");
            }
        } catch (Exception e) {
            return Result.fail("删除群聊消息失败: " + e.getMessage());
        }
    }

    /**
     * 获取群聊消息总数
     * GET /api/group-chat/count?groupId=xxx
     */
    @GetMapping("/count")
    public Result<Map<String, Object>> getGroupMessageCount(@RequestParam Long groupId) {
        try {
            if (groupId == null) {
                return Result.fail("群组ID不能为空");
            }
            
            long count = chatGroupMessageService.getMessageCount(groupId);
            
            Map<String, Object> result = new HashMap<>();
            result.put("groupId", groupId);
            result.put("count", count);
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.fail("获取群聊消息总数失败: " + e.getMessage());
        }
    }
}
